from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.views.generic.list_detail import object_list
from lotto.const import BET, ORDERS, SIZE
from lotto.statistic.forms import ModeForm
from lotto.profile.forms import AddBetForm
from lotto.profile.models import Profile


@login_required ()
def profile (request):
    return render_to_response ('profile/profile.html',
							   context_instance = RequestContext (request));

@login_required ()
def bets (request):
    request.session['sort'] = request.GET.get ('sort', 'desc');
    if request.method == 'POST':
        form = ModeForm (request.POST);
        if form.is_valid ():
            m = form.cleaned_data['mode'];
            request.session['mode'] = m;
    else:
        m = request.session.get ('mode', 'lotto');
        form = ModeForm (initial = {'mode':m});
        
    form.fields['mode'].widget.attrs = {'onchange':"this.form.submit();"};
    aform = AddBetForm (SIZE[m][1]+1, initial = {'mode':m});
    lotto = BET[m].objects.filter (profile__user = request.user).order_by (ORDERS[request.session['sort']]);
    return object_list (request, queryset = lotto,
                        template_name = 'profile/bets.html',
                        paginate_by = 15,
                        template_object_name = 'lottos',
                        extra_context = {'form':form, 'aform':aform});

@login_required ()
def bets_add (request):
    if request.method == 'POST':
        form = AddBetForm (SIZE[request.session.get('mode', 'lotto')][1]+1, request.POST);
        if form.is_valid ():
            d = form.cleaned_data;
            n = request.POST.getlist ('nums');
            if SIZE[d['mode']][0] == len(n):
                try:
                    profile = request.user.profile;
                except Exception:
                    profile = Profile (user = request.user);
                    profile.save ();
                bet = BET[d['mode']] ();
                bet.from_data (datetime.now (), int(d['quantity']),
                               profile, [int(i) for i in n]);
                bet.save ();
    return HttpResponseRedirect ('../');

@login_required ()
def bets_del (request, id):
    m = request.session.get ('mode', 'lotto');
    try:
        bet = BET[m].objects.get (id = id, profile__user = request.user);
        bet.delete ();
    except:
        pass;          
    return HttpResponseRedirect ('../../');

@login_required ()
def settings (request):
    return render_to_response ('profile/settings.html',
							   context_instance = RequestContext (request));
